package com.mission.game.playgame;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.TextView;

import com.mission.game.R;
import com.mission.game.components.StatusAdapter;
import com.mission.game.utils.Mission;
import com.mission.game.utils.Task;

public class PlayMissionScreen extends Activity {
	protected static final int START_TASK = 10;
	private Mission _mission;
	private TextView _missionNameView;
	private TextView _missionDescriptionView;
	private Task _sentTask;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.play_mission_screen);

		_missionNameView = (TextView) findViewById(R.id.mission_name);
		_missionDescriptionView = (TextView) findViewById(R.id.mission_description);

		Bundle extras = getIntent().getExtras();
		_mission = (Mission) extras.getSerializable("mission");
		setFields();

		setTasks();
	}

	private void setFields() {
		_missionNameView.setText(_mission.getName());
		_missionDescriptionView.setText(_mission.getDescription());
	}

	private void setTasks() {
		// Set chosen tasks list
		ListView tasksLv = (ListView) findViewById(R.id.chosen_missions_list);
		StatusAdapter<Task> taskAdapter = new StatusAdapter<Task>(this,
				R.layout.status_list_item, _mission.getTasks());
		tasksLv.setAdapter(taskAdapter);
		tasksLv.setTextFilterEnabled(true);
		tasksLv.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				_sentTask = _mission.getTasks().get(position);
				Intent playTask = new Intent(getApplicationContext(), _sentTask
						.getPlayClass());
				playTask.putExtra("task", _sentTask);
				startActivityForResult(playTask, START_TASK);
			}
		});
	}

	@Override
	protected void onResume() {
		super.onResume();
		setTasks();
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (data != null && data.getExtras() != null && data.getExtras().containsKey("task")) {
			Task task = (Task) data.getExtras().get("task");
			_mission.updateTask(task);
			_mission.updateStatus();
		}
		setTasks();
	}
	
	@Override
	public void onBackPressed() {
		getIntent().putExtra("mission", _mission);
		setResult(RESULT_OK, getIntent());
		finish();
	}
}
